package com.example.demo.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.Swing;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    private Logger log = Logger.getLogger(WebSocketClientHandler.class);
    ConcurrentHashMap<String, ChannelGroup> rooms = new ConcurrentHashMap();
    private static final ChannelGroup CHANNEL_GROUP = new DefaultChannelGroup("ChannelGroups", GlobalEventExecutor.INSTANCE);

    private String btc = "";
    private String eth = "";

    private static String priceMsg = "初始化";
    private static JLabel jLabel;
    private final WebSocketClientHandshaker handshaker;
    private ChannelPromise handshakeFuture;

    public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
        this.handshaker = handshaker;
        create();
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshaker.handshake(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        System.out.println("WebSocket Client disconnected!");
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        Channel ch = ctx.channel();
        if (!handshaker.isHandshakeComplete()) {
            try {
                handshaker.finishHandshake(ch, (FullHttpResponse) msg);
                log.info("WebSocket Client connected!");
                handshakeFuture.setSuccess();
            } catch (WebSocketHandshakeException e) {
                log.info("WebSocket Client failed to connect");
                handshakeFuture.setFailure(e);
            }
            return;
        }

        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            throw new IllegalStateException(
                    "Unexpected FullHttpResponse (getStatus=" + response.status() +
                            ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
        }

        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof PongWebSocketFrame) {
            System.out.println("WebSocket Client received pong");
        } else if (frame instanceof CloseWebSocketFrame) {
            System.out.println("WebSocket Client received closing");
            ch.close();
        } else if (frame instanceof BinaryWebSocketFrame) {
            BinaryWebSocketFrame binaryFrame = (BinaryWebSocketFrame) frame;
            byte[] temp = new byte[binaryFrame.content().readableBytes()];
            binaryFrame.content().readBytes(temp);
            temp = GZipUtils.decompress(temp);
            String str = new String(temp, "UTF-8");
            if (str.contains("ping")) {
                //log.info("send:" + str.replace("ping", "pong"));
                ch.writeAndFlush(new TextWebSocketFrame(str.replace("ping", "pong")));
            }
            JSONObject json = JSON.parseObject(str);
            try {
                if (json.containsKey("tick")) {
                    String ts = json.getString("ts");
                    String chStr = json.getString("ch");
                    String bi = StringUtils.substring(chStr, chStr.indexOf(".") + 1, chStr.indexOf(".kline")).replace("usdt", "");
                    String tick = json.getString("tick");
                    JSONObject json2 = JSONObject.parseObject(tick);
                    String close = json2.getString("close");
                    Date date = new Date(Long.valueOf(ts));
                    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                    //log.info("----:"+format.format(date)+"---"+bi+"----:"+close.substring(0,8));
                    // System.out.println(format.format(date) + "---" + bi + "----:" + close);

                    if (bi.equals("btc")) {
                        btc = close;
                    } else if (bi.equals("eth")) {
                        eth = close;
                    }
                   //priceMsg = "<html>↑:<span  >" + btc + "K/s</span><br>↓:<span  >" + eth + "K/s</span><br>time:<span >" + format.format(date) + "</span><html>";
                    priceMsg = "<html>↑:<span  >" + btc + "K/s</span><br>↓:<span  >" + eth + "K/s</span><html>";
                    jLabel.setText(priceMsg);
                } else {
                    log.info("receive:" + json.toJSONString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        ctx.close();
    }


    public static void create() {
        JFrame jFrame = new JFrame();
        // TODO Auto-generated method stub
        //jFrame.setOpacity(0.5f);
        jFrame.setLayout(new BorderLayout());
        //is.setLayout(new GridLayout(2,2,10,5)); //默认为1行，n列；2行3列，水平间距10，垂直间距5
        //this.setLayout(new GridLayout(2, 2, 10, 30));
        jFrame.setUndecorated(true);
        //Border b = new CompoundBorder(new EtchedBorder(), new LineBorder(Color.RED));
        JPanel panel = new JPanel();
       // panel.setSize(100, 30);
        //panel.setBorder(b);：
        jLabel = new JLabel("<html>初始化中...<html>");
        panel.add(jLabel);

//输入框取出，待开发
//        JTextField username = new JTextField();
//        username.setColumns(10);
        //this.add(username, BorderLayout.NORTH);


        //鼠标拖动监听
        mouseMotionListener(panel, jFrame);
        jFrame.setLocation(0, 0);
        jFrame.getContentPane().add(panel);
        jFrame.setSize(100, 50);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setAlwaysOnTop(true);
        jFrame.setOpacity(0.5f);
        jFrame.show();
        addSystemTray(jFrame);
    }

    public static void mouseMotionListener(JPanel panel, Frame frame) {
        panel.addMouseMotionListener(new MouseAdapter() {
            private boolean top = false;
            private boolean down = false;
            private boolean left = false;
            private boolean right = false;
            private boolean drag = false;
            private Point lastPoint = null;
            private Point draggingAnchor = null;

            @Override
            public void mouseMoved(MouseEvent e) {
                if (e.getPoint().getY() == 0) {
                    frame.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
                    top = true;
                } else if (Math.abs(e.getPoint().getY() - frame.getSize().getHeight()) <= 1) {
                    frame.setCursor(Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
                    down = true;
                } else if (e.getPoint().getX() == 0) {
                    frame.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                    left = true;
                } else if (Math.abs(e.getPoint().getX() - frame.getSize().getWidth()) <= 1) {
                    frame.setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                    right = true;
                } else {
                    frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                    draggingAnchor = new Point(e.getX() + panel.getX(), e.getY() + panel.getY());
                    top = false;
                    down = false;
                    left = false;
                    right = false;
                    drag = true;
                }

            }

            @Override
            public void mouseDragged(MouseEvent e) {
                Dimension dimension = frame.getSize();
                if (top) {

                    dimension.setSize(dimension.getWidth(), dimension.getHeight() - e.getY());
                    frame.setSize(dimension);
                    frame.setLocation(frame.getLocationOnScreen().x, frame.getLocationOnScreen().y + e.getY());
                } else if (down) {

                    dimension.setSize(dimension.getWidth(), e.getY());
                    frame.setSize(dimension);

                } else if (left) {

                    dimension.setSize(dimension.getWidth() - e.getX(), dimension.getHeight());
                    frame.setSize(dimension);


                    frame.setLocation(frame.getLocationOnScreen().x + e.getX(), frame.getLocationOnScreen().y);

                } else if (right) {

                    dimension.setSize(e.getX(), dimension.getHeight());
                    frame.setSize(dimension);
                } else {
                    frame.setLocation(e.getLocationOnScreen().x - draggingAnchor.x, e.getLocationOnScreen().y - draggingAnchor.y);
                }
            }
        });

    }

    public static void addSystemTray(Frame frame) {
        /*
         * 添加系统托盘
         */
        if (SystemTray.isSupported()) {
            // 获取当前平台的系统托盘
            SystemTray tray = SystemTray.getSystemTray();

            // 加载一个图片用于托盘图标的显示
//            Image image = Toolkit.getDefaultToolkit().getImage("/pic.jpg");
//
            URL imgUrl = Swing.class.getClassLoader().getResource("pic.jpg");
////            // 通过getImage()函数获取图片
            Image image = Toolkit.getDefaultToolkit().getImage(imgUrl);


            // 创建点击图标时的弹出菜单
            PopupMenu popupMenu = new PopupMenu();

            MenuItem openItem = new MenuItem("打开");
            MenuItem exitItem = new MenuItem("退出");

            openItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 点击打开菜单时显示窗口
                    if (!frame.isShowing()) {
                        frame.setVisible(true);
                    }
                }
            });
            exitItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // 点击退出菜单时退出程序
                    System.exit(0);
                }
            });

            popupMenu.add(openItem);
            popupMenu.add(exitItem);

            // 创建一个托盘图标
            TrayIcon trayIcon = new TrayIcon(image, "这是一个托盘图标", popupMenu);

            // 托盘图标自适应尺寸
            trayIcon.setImageAutoSize(true);

            trayIcon.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("托盘图标被右键点击");
                }
            });
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    switch (e.getButton()) {
                        case MouseEvent.BUTTON1: {
                            System.out.println("托盘图标被鼠标左键被点击");
                            break;
                        }
                        case MouseEvent.BUTTON2: {
                            System.out.println("托盘图标被鼠标中键被点击");
                            break;
                        }
                        case MouseEvent.BUTTON3: {
                            System.out.println("托盘图标被鼠标右键被点击");
                            break;
                        }
                        default: {
                            break;
                        }
                    }
                }
            });

            // 添加托盘图标到系统托盘
            try {
                tray.add(trayIcon);
            } catch (AWTException e) {
                e.printStackTrace();
            }

        } else {
            System.out.println("当前系统不支持系统托盘");
        }
    }


}

